package apigateway.project.core.predicate;


import apigateway.project.commen.config.Rule;
import apigateway.project.commen.exception.ResponseException;
import apigateway.project.core.context.GlobalContext;
import apigateway.project.core.request.GlobalRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
@Slf4j
public class GatewayPredicateChain {
    private List<Predicate> predicates = new ArrayList<Predicate>();

    public GatewayPredicateChain addPredicate(Predicate predicate) {
        predicates.add(predicate);
        return this;
    }

    public GatewayPredicateChain addPredicates(List<Predicate> predicates) {
        predicates.addAll(predicates);
        return this;
    }
    public boolean doPredicates(GlobalRequest request, Rule rule) {
        if(predicates.isEmpty()) {return true;}

        try {
            for(Predicate predicate : predicates) {
                predicate.doPredicate(request, rule);
            }
        } catch (Exception e) {
            if(e instanceof ResponseException){
                //断言不匹配->不匹配这个路由规则,直接返回false
                return false;
            }
            log.error("断言异常:{}",e.getMessage());
            return false;
        }
        return true;
    }
}
